package com.rchat.pocmini.activity.location;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.airtalkee.sdk.AirtalkeeAccount;
import com.airtalkee.sdk.entity.AirContact;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;
import com.rchat.pocmini.R;
import com.rchat.pocmini.activity.bean.ClistBean;
import com.rchat.pocmini.activity.fragment.groups.GroupsPresenterImpl;
import com.rchat.pocmini.activity.view.HorizontalListView;
import com.rchat.pocmini.common.mvp.BaseMvpActivity;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ljd on 2017/9/28.
 */

public class LocationMvpActivity extends BaseMvpActivity<LocationPresenterImpl,LocationModelImpl> implements LocationContract.View{

    @BindView(R.id.bmapView)
    MapView mMapView;

    @BindView(R.id.iv_location_talk)
    ImageView talkIv;

    @BindView(R.id.ll_head)
    LinearLayout llHead;

    @BindView(R.id.lv_horizon)
    HorizontalListView lvHorizon;//横向的成员显示列表

    private MemberListAdapter lvHorizonAdapter;


    private TextView mNameInMap; //成员在地图上显示的名称

    LayoutInflater mInflate;

    private View mapHeadView;


    private String groupId;
    private String groupName;

    private BaiduMap mBaiduMap;

    private List<AirContact> mMemberList ;

    private Marker mMarker;
    private ConcurrentHashMap<String, Marker> mMarkers = new ConcurrentHashMap<String, Marker>();
    private ConcurrentHashMap<String, Marker> mMarkerPoss = new ConcurrentHashMap<String, Marker>();

    @Override
    public void initPresenter() {
        mMemberList = new ArrayList<>();
        lvHorizonAdapter = new MemberListAdapter(this,mMemberList);
        lvHorizon.setAdapter(lvHorizonAdapter);

        lvHorizon.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mPresenter.horizonListOnItemClick(parent,view,position,id,mMarkers);
            }
        });
        mPresenter.setVM(this,mModel);
    }

    @Override
    public int getLayoutId() {
        return R.layout.location_activity_layout;
    }

    @Override
    public void initView() {
        mPresenter.reqLocationReport10S();
        groupId = getIntent().getStringExtra(GroupsPresenterImpl.KEY_GROUPID);
        groupName = getIntent().getStringExtra("groupName");
        mInflate =  LayoutInflater.from(this);
        mapHeadView = getLayoutInflater().inflate(R.layout.map_head_view, null);
        mNameInMap = (TextView) mapHeadView.findViewById(R.id.tv_map_name);

        mMapView.showZoomControls(false);
        mBaiduMap = mMapView.getMap();

        // 开启定位图层
        mPresenter.initOrientationListener();

        mBaiduMap.setMyLocationEnabled(true);
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {

            @Override
            public boolean onMarkerClick(Marker arg0) {
                mPresenter.showMemberDetailDialog(arg0,mMemberList,mMarker);
                return false;
            }
        });

        llHead.getBackground().setAlpha(80);

        talkIv.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    mPresenter.reqTalkRelease();
                }
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    mPresenter.reqTalk();
                }
                return true;
            }
        });
    }

    @OnClick({R.id.iv_location_back,
              R.id.ori_location})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_location_back:
                doGoBack();
                break;
            case R.id.ori_location:
                mPresenter.oriLocation();
                break;
        }
    }

    @Override
    public void doAfterInitView() {

    }

    @Override
    public void showMember(AirContact airContact) {
        mMemberList.add(airContact);
        lvHorizonAdapter.notifyDataSetChanged();
    }

    @Override
    public void showTalkIv(int resId) {
        talkIv.setImageResource(resId);
    }

    @Override
    public void setLocationData(MyLocationData locData) {
        mBaiduMap.setMyLocationData(locData);
    }

    @Override
    public void setLocationConfiguration(MyLocationConfiguration configuration,LatLng latLng) {
        mBaiduMap.setMyLocationConfigeration(configuration);

        if (mMarker == null) {
            mNameInMap.setText(AirtalkeeAccount.getInstance().getUserName());
            BitmapDescriptor bd = BitmapDescriptorFactory.fromView(mapHeadView);
            MarkerOptions ooA = new MarkerOptions().position(latLng).icon(bd);
            Bundle b = new Bundle();
            b.putString("id", AirtalkeeAccount.getInstance().getUserId());
            ooA.extraInfo(b);
            mMarker = (Marker) mBaiduMap.addOverlay(ooA);
        } else {
            mMarker.setPosition(latLng);
        }
    }

    @Override
    public void targetToLatLng(LatLng latLng, boolean isNeedZoom) {
        MapStatus.Builder builder = new MapStatus.Builder();
        builder.target(latLng);
        if (isNeedZoom) {
            builder.zoom(18.0f);
        }
        mBaiduMap.animateMapStatus(MapStatusUpdateFactory
                .newMapStatus(builder.build()));
    }

    private LatLng latlng;

    @Override
    public void updateOverlay(List<ClistBean> list,AirContact mAirContact) {
        if (mMapView == null) {
            return;
        }

        Set<String> newKeys = new HashSet<String>();
        Set<String> oldInKeys = mMarkers.keySet();
        mMemberList.clear();
        mMemberList.add(mAirContact);
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getUid().equals(AirtalkeeAccount.getInstance().getUserId())) {
                continue;
            }
            newKeys.add(list.get(i).getUid());
            AirContact airContact = new AirContact();
            airContact.setIpocId(list.get(i).getUid());
            airContact.setDisplayName(list.get(i).getUsername());
            latlng = new LatLng(Double.parseDouble(list.get(i)
                    .getLatitude()), Double.parseDouble(list.get(i)
                    .getLongitude()));
            mMemberList.add(airContact);
        }
        lvHorizonAdapter.notifyDataSetChanged();

        for (String key : oldInKeys) {
            if (newKeys.contains(key)) {
                //替换
            } else {
                if (mMapView != null) {
                    Marker val = mMarkers.get(key);
                    val.remove();
                    val = null;
                    mMarkers.remove(key);

                    Marker valPos = mMarkerPoss.get(key);
                    valPos.remove();
                    valPos = null;
                    mMarkerPoss.remove(key);
                }
            }
        }


        for (int i = 0; i < list.size(); i++) {
            ClistBean clist = list.get(i);
            if (mMapView != null) {
                latlng = new LatLng(Double.parseDouble(clist
                        .getLatitude()), Double.parseDouble(clist
                        .getLongitude()));
                if (mMarkers.containsKey(clist.getUid())) {
                    Marker mk = mMarkers.get(clist.getUid());
                    mk.setPosition(latlng);

                    Marker mkPos = mMarkerPoss.get(clist.getUsername());
                    if (mkPos != null) {
                        mkPos.setPosition(latlng);
                        mkPos.setRotate(Float.parseFloat(clist.getDirection()));
                        mkPos.setAnchor(0.5f, 0.5f);
                    }
                } else {
                    if (clist.getUid().equals(AirtalkeeAccount.getInstance().getUserId())) {
                        continue;
                    }

                    BitmapDescriptor bdPos = BitmapDescriptorFactory.fromResource(R.drawable.icon_map_diracton_his);
                    MarkerOptions ooPos = new MarkerOptions().position(latlng).icon(bdPos)
                            .anchor(0.5f, 0.5f).rotate(Float.parseFloat(clist.getDirection()));
                    Bundle b = new Bundle();
                    b.putString("id", clist.getUid());
                    ooPos.extraInfo(b);
                    Marker mkPos = (Marker) (mBaiduMap.addOverlay(ooPos));
                    mMarkerPoss.put(clist.getUid(), mkPos);

                    mNameInMap.setText(clist.getUsername());
                    BitmapDescriptor bd = BitmapDescriptorFactory.fromView(mapHeadView);
                    MarkerOptions ooA = new MarkerOptions().position(latlng).icon(bd);
                    ooA.extraInfo(b);
                    Marker mk = (Marker) (mBaiduMap.addOverlay(ooA));
                    mMarkers.put(clist.getUid(), mk);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBaiduMap.clear();
        mPresenter.cancelLocationReport10S();
    }
}
